/*
 * Dijjer - A Peer to Peer HTTP Cache
 * Copyright (C) 2004,2005 Change.Tv, Inc
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package dijjer.io.comm;

import java.net.DatagramPacket;

import dijjer.AbstractFactory;
import dijjer.updater.ResourceManager;
import dijjer.util.AbstractThread;
import dijjer.util.logging.Logger;

public class MulticastSocketManager extends AbstractThread {

	public static final String VERSION = "$Id: MulticastSocketManager.java 33 2009-03-20 13:26:16Z mathias.demare $";
	private Dispatcher _dispatcher;
	private boolean _isDone = false;
	private static MulticastSocketManager _mcsm;
	private final int _listenPort;

	public MulticastSocketManager(int listenPort) throws Exception {
		_listenPort = listenPort;
		startThread();
		getBaseThread().setName("MulticastSocketManager listener thread on port " + listenPort);
	}

	protected boolean loop() throws InterruptedException { // Listen for packets
		DatagramPacket packet = ResourceManager.receiveMC(_listenPort);

		// Check for matched _filters
		if (packet != null) {
			checkFilters(packet);
		}
		return true;
	}

	protected void cleanUp() {
		synchronized (this) {
			_isDone = true;
			notifyAll();
		}
	}

	private void checkFilters(DatagramPacket packet) {
		Message m = null;
		try {
			m = Message.decodeFromPacket(packet);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.error("Couldn't parse packet from " + packet.getAddress());
			return;
		}
		// No message, or one we sent to the multicast group
		if ((m == null)
			|| (m.getSpec().equals(DMT.whoAreYou)
				&& ((WebPeer) m.getSource()).getPort() == ResourceManager.mcastPort)
				&& ((WebPeer)m.getSource()).getAddress().equals(
						((WebPeer)AbstractFactory.getFactory().getRoutingTable().getPeer()).getAddress())) {
			return;
		}

		if (m.getSpec().equals(DMT.ping)
			|| m.getSpec().equals(DMT.pong)
			|| m.getSpec().equals(DMT.packetTransmit)
		) {
			Logger.debug("" + (System.currentTimeMillis() % 60000) + " " + _listenPort + " <- "
					+ m.getSource() + " : " + m);
		} else {
			Logger.info("" + (System.currentTimeMillis() % 60000) + " " + _listenPort + " <- "
					+ m.getSource() + " : " + m);
		}
		
		if (_dispatcher == null) {
			setDispatcher(Dispatcher.getDispatcher());
		}

        boolean matched = MessageFilter.checkFilters(m);
        // Feed unmatched messages to the dispatcher
		if (!matched && (_dispatcher != null)) {
			try {
				matched = _dispatcher.handleMessage(m);
			} catch (Exception e) {
				Logger.error("Error handling message: "+ m, e);
			}
		}
		// Keep the last few _unclaimed messages around in case the intended receiver isn't receiving yet
		if (!matched) {
			Logger.info("Received unclaimed message "+m+", adding to unclaimed pile");
            MessageFilter.addUnclaimed(m);
		}
	}

	public void shutdown(boolean exit) {
		synchronized (this) {
			while (!_isDone) {
				try {
					wait(2000);
				} catch (InterruptedException e) {
					Logger.error(e);
				}
			}
		}
	}

	public void setDispatcher(Dispatcher d) {
		_dispatcher = d;
	}

	public String toString() {
		return ResourceManager.getMCSocketString(_listenPort);
	}

	public static MulticastSocketManager getMulticastSocketManager()
	{
		return _mcsm;
	}

	public static void init(int externalListenPort)
	    throws Exception
	{
		_mcsm = new MulticastSocketManager(externalListenPort);
	}
}